package cn.krund.lyc.hotlerobot.utils;

import org.json.JSONObject;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLEncoder;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

/**
 * @包名: cn.krund.lyc.hotlerobot.utils
 * @作者: 刘育成
 * @时间: 2018/4/5  15:10
 * @org: 克路德人工智能
 * @描述: TODO
 * @fileName: HttpUtil
 */

public class HttpUtil {

    //Get请求的方法
    public static String sendGet(String url, String param) {
        String result = "";
        BufferedReader in = null;
        try {
            String urlNameString = url;
            if (param != null && param != "") {
                urlNameString += "?" + param;
            }
            URL realUrl = new URL(urlNameString);
            // 打开和URL之间的连接
            URLConnection connection = realUrl.openConnection();
            // 设置通用的请求属性
            connection.setRequestProperty("accept", "*/*");
            connection.setRequestProperty("connection", "Keep-Alive");
            connection.setRequestProperty("user-agent",
                    "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
            // 建立实际的连接
            connection.connect();
            // 获取所有响应头字段
            Map<String, List<String>> map = connection.getHeaderFields();
            // 遍历所有的响应头字段
            for (String key : map.keySet()) {
                System.out.println(key + "--->" + map.get(key));
            }
            // 定义 BufferedReader输入流来读取URL的响应
            in = new BufferedReader(new InputStreamReader(
                    connection.getInputStream()));
            String line;
            while ((line = in.readLine()) != null) {
                result += line;
            }
        } catch (Exception e) {
//            //如果连接公司服务端失败，则用百度的GPS定位获得城市
//            result=locationCityByIp();
//            System.out.println("发送GET请求出现异常！" + e);
//            e.printStackTrace();
        }
        // 使用finally块来关闭输入流
        finally {
            try {
                if (in != null) {
                    in.close();
                }
            } catch (Exception e2) {
                e2.printStackTrace();
            }
        }
        if (result == null) {
//            result=locationCityByIp();
        }
        return result;
    }

    //post提交的方法
    public static String postStream(String str_url, Map<String, String> map) {
        String retValue = "";
        HttpURLConnection httpConn = null;

        try {
            URL url = new URL(str_url);
            httpConn = (HttpURLConnection) url.openConnection();
            httpConn.setDoOutput(true);
            httpConn.setDoInput(true);
            httpConn.setUseCaches(false);
            httpConn.setRequestMethod("POST");
            JSONObject jsonObject = new JSONObject(map);
            String postJson = jsonObject.toString();
            byte[] requestStringBytes = postJson.getBytes("utf-8");
            httpConn.setRequestProperty("Content-length", "" + requestStringBytes.length);
            httpConn.setRequestProperty("Charset", "UTF-8");
            httpConn.setConnectTimeout(5000);
            httpConn.setReadTimeout(500);
            String name = URLEncoder.encode("kelude", "utf-8");
            Iterator outputStream = map.entrySet().iterator();

            while (outputStream.hasNext()) {
                Map.Entry responseCode = (Map.Entry) outputStream.next();
                httpConn.setRequestProperty((String) responseCode.getKey(), (String) responseCode.getValue());
            }

            httpConn.connect();
            OutputStream outputStream1 = httpConn.getOutputStream();
            outputStream1.write(requestStringBytes);
            outputStream1.close();
            int responseCode1 = httpConn.getResponseCode();
            if (200 == responseCode1) {
                StringBuffer sb = new StringBuffer();
                BufferedReader responseReader = new BufferedReader(new InputStreamReader(httpConn.getInputStream(), "utf-8"));

                String readLine;
                while ((readLine = responseReader.readLine()) != null) {
                    sb.append(readLine).append("\n");
                }
                responseReader.close();
                httpConn.getInputStream().close();
                retValue = sb.toString();
            }
        } catch (Exception var18) {
            LogUtils.debug("var18错误！");
        } finally {
            if (httpConn != null) {
                httpConn.disconnect();
            }
        }
        return retValue;
    }
}

